<template>
    <div class="Table">


        <!-- <el-button @click="TestFn">
            TestFn
        </el-button> -->


        <div class="row">
            <div>
                <span>全体図</span>
                <el-select class="form-ipt" v-model="MapValue" @change="MapValueChange">
                    <el-option v-for=" item in MapList" :key="item.areaCode" :label="item.areaName"
                        :value="item.areaCode"></el-option>
                </el-select>
                <span>装置</span>
                <el-input class="form-ipt" readonly v-model="allLabel.pltName"></el-input>
                <span>処理系</span>
                <el-input class="form-ipt" readonly v-model="allLabel.proName"></el-input>
            </div>

            <div class="bottonBtn">

                <el-button type="primary" size="mini" @click="OKFn">
                    OK
                </el-button>
                <el-button size="mini" @click="exitFn">
                    閉じる
                </el-button>
            </div>
        </div>

        <div id="right-CAD1" class="right-CAD1" ref="rightCAD1"></div>
    </div>
</template>

<script>
import $ from "jquery";
import { getFullFieldMapList, getFullFieldMark, getPlatInfoByArea } from "@/api/api";
import { getLocalStorage } from "@/utils/storage";
import eventBus from "@/eventBus/bus";
import _ from 'lodash-es';
import { showLoading, hideLoading } from "@/utils/loading";
import * as svg_opt from "@/utils/svg_opt.js";
export default {
    name: "DeviceLoginIndex",
    data() {
        return {

            MapList: [],
            MapValue: 8,
            pfdData: [],
            sourceUrl: '',

            activeMackUp: null,

            allLabel: {
                "areaCode": 0,
                "areaNo": 0,
                "pltCode": 0,
                "proCode": 0,
                "pltName": "",
                "proName": ""
            }

        };
    },
    components: {
    },
    props: [],// 1列表2列表-图形
    watch: {

    },
    methods: {
        TestFn() {
            this.getFullFieldMapListApi();
        },
        OKFn() {
            // 不明原因，allLabel会空
            if (Object.keys(this.allLabel).length == 0) {
                this.exitFn();
                return
            }
            this.$emit('panorFn', false);
            try {
                if (this.allLabel.pltCode == 0 && this.allLabel.proCode == 0) {
                    eventBus.$emit('panOrView', 'No Data');
                    return
                }
                eventBus.$emit('panOrView', this.allLabel);
            } catch (error) {

            }

        },

        exitFn() {
            this.$emit('panorFn', false);
            eventBus.$emit('panOrView', 'No Data');
        },


        // 右侧图形逻辑
        // 获取右侧下拉框
        async getFullFieldMapListApi() {
            console.log('123');
            let dataJson = {};
            let res = await getFullFieldMapList(dataJson)
            this.MapList = [];
            if (res.data.code != 0) {
                return;
            }
            this.MapList = res.data.data;
            this.MapValue = this.MapList[0].areaCode;
            // svg图处理
            this.svgStartFn(this.MapList[0].areaFile);
            this.getFullFieldMarkApi(this.MapList[0].areaCode);

        },
        async MapValueChange(value) {
            let areaFile = this.MapList.filter(item => item.areaCode == value)[0].areaFile || '';
            console.log('areaFile', areaFile);
            // areaFile = 'http://192.168.33.89:8085\\aaa\\pfd\\web\\PFD.svg';
            this.svgStartFn(areaFile, value);

            // this.getPfdByPlantApi(value);

            this.activeMackUp = null;
        },
        // svg开始处理入口
        svgStartFn(inSourceUrl, value) {
            showLoading();
            if (inSourceUrl == null || typeof inSourceUrl == "undefined") {
                svg_opt.removeSvg();
                return;
            }
            let num = inSourceUrl.lastIndexOf(".") + 1;
            this.sourceExt = inSourceUrl.substring(num);
            this.sourceUrl = inSourceUrl;

            let EXT = this.sourceExt
            if (
                EXT == "png" ||
                EXT == "jpg" ||
                EXT == "gif" ||
                EXT == "bmp" ||
                EXT == "jpeg" ||
                EXT == "tif" ||
                EXT == "tiff"
            ) {
                this.isSourcePic = true;
                this.svgSourceUrl = require("@/assets/model/method-draw-image.svg");
            } else {
                this.isSourcePic = false;
                this.svgSourceUrl = inSourceUrl;
            }

            if (!this.svgSourceUrl || this.svgSourceUrl == "") {
                svg_opt.removeSvg();
                $('.right-CAD1').html('NO Data');
                $('.right-CAD1').css({
                    'display': 'flex',
                    'align-items': 'center',
                    'justify-content': 'space-evenly',
                    'font-size': '15px'
                });
                return;
            } else {
                // fetch(this.svgSourceUrl)
                //     .then(async response => {
                //         // 处理响应的数据
                //         if (response.status != 200) {
                //             svg_opt.removeSvg();
                //             $('.right-CAD1').html('NO Data');
                //             $('.right-CAD1').css({
                //                 'display': 'flex',
                //                 'align-items': 'center',
                //                 'justify-content': 'space-evenly',
                //                 'font-size': '15px'
                //             });
                //             return
                //         }
                //         window.open(this.currentItem.path);
                //     })
                //     .catch(async error => {
                //     });
            }



            this.isSvgLoading = true;
            svg_opt.setSvgLineWidthRatio(1.5);
            svg_opt.setSvgBoundingBoxRatio(0, 0, 1);
            svg_opt.setCanClickSelectMarkup(true);

            svg_opt.setCanEditSelectMarkup(false);
            svg_opt.setCanFitPositionAndScale(false);
            svg_opt.setEditDotWidthRatio(3);
            hideLoading();
            svg_opt.AddSvg(this.svgSourceUrl, "right-CAD1", this.onSvgMousePosChange, true,
                    0,
                    0,
                    this.sourceExt == "wmf" ? 1 : -1);
            svg_opt.SetSvgMouseMode(0);
            svg_opt.setLoadCallBack(this.onSvgLoaded);
            svg_opt.setSelectCallBack(this.onLineGroupSelect);
            console.log(this.svgSourceUrl);

            setTimeout(() => {
                this.getFullFieldMarkApi(value);
            }, 1500);

        },
        // svg加载失败处理
        onSvgLoaded(error) {
            console.log("onSvgLoaded --- ", error);
            this.isSvgLoading = false;
            hideLoading();
            if (error) {
                console.log(error);
                return;
            }

            this.isSvgLoaded = true;

            if (this.isSourcePic) {
                svg_opt.changeSvgElementData({
                    tagName: "img-content",
                    paramName: "xlink:href",
                    newValue: this.sourceUrl
                });
            }
        },
        // 获取MarkUp数据
        async getFullFieldMarkApi(AreaCode) {
            showLoading()
            let dataJson = {
                AreaCode: AreaCode || this.MapValue
            };
            let res = await getFullFieldMark(dataJson);
            try {
                res.data.data.forEach(item => {
                    item.areaCode = Number(item.areaCode);
                    item.areaNo = Number(item.areaNo);
                    item.areaType = Number(item.areaType);
                    item.dtlNo = Number(item.dtlNo);
                    item.prlFntsiz = Number(item.prlFntsiz);
                    item.prlWidth = Number(item.prlWidth);
                    item.prlX = Number(item.prlX);
                    item.prlY = Number(item.prlY);
                    item.prlNo = Number(item.areaNo);
                    item.prlType = Number(item.areaType);
                    item.title = item.proName;
                })
            } catch (error) {

            }
            this.pfdData = [];
            if (res.data.code != 0) {
                return;
            }
            this.pfdData = res.data.data;
            // 模拟数据

            this.pfdData = this.genLineGroupAndShow(this.pfdData);
            console.log('this.pfdData 1111', this.pfdData);
            // svg_opt.clearAllMarkups();

            // 绘制线组
            setTimeout(() => {
                svg_opt.testAddLineGroupsByParams(this.pfdData);
                hideLoading();

            }, 500);
        },
        /**
         * 处理线组数据
         */
        genLineGroupAndShow(originData) {
            let lineGroups = [];
            let lastPrl = "";

            console.log(originData);
            console.log(this.isSourcePic);

            // 遍历节点
            for (let i = 0; i < originData.length; i++) {
                let tempData = originData[i];
                let tempLineGroup = null;

                // 如果当前节点与上一个节点的线组号不同，新建线组，压入线组list
                if (lastPrl != tempData.prlNo) {
                    tempLineGroup = {};
                    lineGroups.push(tempLineGroup);

                    tempLineGroup.defaultLineColor = "#0000ff11";
                    tempLineGroup.defaultLineWidth = "10";
                    tempLineGroup.prlNo = tempData.prlNo;
                    tempLineGroup.groupItems = [];
                    tempLineGroup.sId = tempData.prlNo;
                    tempLineGroup.fEntType = "17";
                }

                // 取最近一个线组
                tempLineGroup = lineGroups[lineGroups.length - 1];

                // 如果线组为空 根据当前节点创建
                if (
                    tempLineGroup.groupItems.length == 0 ||
                    tempLineGroup.groupItems[
                        tempLineGroup.groupItems.length - 1
                    ].dtlNo != tempData.dtlNo
                ) {
                    let newItem = {};
                    newItem.dtlNo = tempData.dtlNo;
                    newItem.shapeType =
                        tempData.prlType == 1
                            ? "line"
                            : tempData.prlType == 2
                                ? "closeline"
                                : "rect";
                    newItem.fEntType = "17";
                    newItem.text = `${tempData.pltName} ${tempData.proName == 'No related' ? '' : ' :  ' + tempData.proName}`;
                    newItem.points = [];
                    if (this.isSourcePic) {
                        newItem.points.push({
                            x: tempData.prlX,
                            y: 0 - Math.abs(tempData.prlY),
                        });
                    } else {
                        newItem.points.push({
                            x: tempData.prlX,
                            y: tempData.prlY,
                        });
                    }
                    tempLineGroup.groupItems.push(newItem);
                } else if (
                    tempLineGroup.groupItems[
                        tempLineGroup.groupItems.length - 1
                    ].dtlNo == tempData.dtlNo &&
                    tempLineGroup.groupItems[
                        tempLineGroup.groupItems.length - 1
                    ].points.length >= 2
                ) {
                    let newItem = {};
                    newItem.dtlNo = tempData.dtlNo;
                    newItem.shapeType =
                        tempData.prlType == 1
                            ? "line"
                            : tempData.prlType == 2
                                ? "closeline"
                                : "rect";
                    newItem.fEntType = "17";
                    newItem.points = [];

                    newItem.points.push(
                        tempLineGroup.groupItems[
                            tempLineGroup.groupItems.length - 1
                        ].points[
                        tempLineGroup.groupItems[
                            tempLineGroup.groupItems.length - 1
                        ].points.length - 1
                        ]
                    );

                    if (this.isSourcePic) {
                        newItem.points.push({
                            x: tempData.prlX,
                            y: 0 - Math.abs(tempData.prlY),
                        });
                    } else {
                        newItem.points.push({
                            x: tempData.prlX,
                            y: tempData.prlY,
                        });
                    }
                    tempLineGroup.groupItems.push(newItem);
                } else if (
                    tempLineGroup.groupItems[
                        tempLineGroup.groupItems.length - 1
                    ].dtlNo == tempData.dtlNo
                ) {
                    if (this.isSourcePic) {
                        // newItem.points.push({ x: tempData.prlX, y: 0 - Math.abs(tempData.prlY) });
                        tempLineGroup.groupItems[
                            tempLineGroup.groupItems.length - 1
                        ].points.push({
                            x: tempData.prlX,
                            y: 0 - Math.abs(tempData.prlY),
                        });
                    } else {
                        // newItem.points.push({ x: tempData.prlX, y: tempData.prlY });
                        tempLineGroup.groupItems[
                            tempLineGroup.groupItems.length - 1
                        ].points.push({ x: tempData.prlX, y: tempData.prlY });
                    }
                }

                lastPrl = tempLineGroup.prlNo;
            }

            // lineGroups[0].groupItems
            console.log(lineGroups)
            return lineGroups;
        },
        /**
     * 线组选中
     */
        async onLineGroupSelect(e) {

            let dataJson = {
                AreaCode: Number(this.MapValue),
                AreaNo: e.prlNo
            };
            let res = await getPlatInfoByArea(dataJson);
            console.log('this.activeMackUp', this.activeMackUp);
            if (res.data.cdoe == -310) {
                this.allLabel = {}
            }
            this.allLabel = res.data.data;
            this.activeMackUp = e;

        },






        // 开始
        initFn() {
            svg_opt.removeSvg();
            this.allLabel = {
                "areaCode": 0,
                "areaNo": 0,
                "pltCode": 0,
                "proCode": 0,
                "pltName": "",
                "proName": ""
            }
            setTimeout(() => {
                this.getFullFieldMapListApi();
            }, 300);

        }

    },
    created() { },
    mounted() {

    },
    beforeDestroy() {

    },
    destroyed() { },
};
</script>
<style lang="scss" scoped>
.Table {
    height: 100%;
    border-top: 1px solid #e1e1e1;
    padding-top: 12px;
    background-color: #FFF;

    .row {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 5px 20px;

        div {
            display: flex;
            align-items: center;

            span {
                margin-right: 12px;
                margin-left: 18px;
            }

            .form-ipt {
                width: 200px;
                height: 24px;

                ::v-deep .el-input__inner {
                    height: 24px;
                    background: #fff;
                }

                ::v-deep .el-input__icon {
                    line-height: 24px;
                }
            }
        }
    }

    .right-CAD1 {
        width: 100%;
        height: 90%;
        cursor: pointer;
        position: relative;

    }
}
</style>